from __future__ import division
import os
import wx
import wx.lib.scrolledpanel as scrolled
import subprocess
 
AppName = "Screenshot Viewer for Minecraft"
Version = "0.5.1"
ThumbWidth = 100
ThumbHeight = 100

TopFrame = None

def SizeFrame():
    global TopFrame
    TopFrame.SendSizeEvent()
    
class  MSVFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)
        
        self.shotpath = ""
        self.CurrentImage = ""
        
        self.Bind(wx.EVT_SIZE, self.OnSize)
        menuBar = wx.MenuBar()

        menu1 = wx.Menu()
        menu1.Append(101, "&Refresh", "Refresh List")
        menu2 = wx.Menu()
        menu2.Append(102, "&About", "About")
        menu3 = wx.Menu()
        menu3.Append(104, "&Open Folder", "Open Folder")
        
        menuBar.Append(menu1, "File")
        menuBar.Append(menu3, "Tools")
        menuBar.Append(menu2, "Help")
        
        self.logtb = wx.TextCtrl(self, -1, "",
                       size=(640, 480), style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)
        self.picpanel = ThumbsPanel(self)
        
        self.imageCtrl = wx.StaticBitmap(self, wx.ID_ANY)
        self.SetImage(wx.EmptyImage(640,480))
        self.SetAutoLayout(True)
        self.SetMenuBar(menuBar)
        self.Bind(wx.EVT_MENU, self.RefreshList, id=101)
        self.Bind(wx.EVT_MENU, self.About, id=102)
        self.Bind(wx.EVT_MENU, self.OpenFolder, id=104)
        self.SetSize((640,480))
        
        self.FindScreenshotPath()
        
        #wx.FutureCall(500, self.ShowMessage)
        
    def FindScreenshotPath(self):
        home = os.getenv('USERPROFILE') or os.getenv('HOME')
        self.Log(" OS[" + os.name + "]\r\n")
        self.Log("User folder [" + home + "]\r\n")
        if os.name=="nt":
            self.shotpath = os.path.join(home, "AppData\Roaming\.minecraft\screenshots")
        else:
            self.shotpath = os.path.join(home, ".minecraft\screenshots")
    def ShowMessage(self):
        dlg = wx.MessageDialog(self, "Refresh the screenshot list?",
                AppName, wx.YES | wx.NO | wx.ICON_QUESTION)
        if dlg.ShowModal() == wx.ID_YES:
            self.Refresh(None)
        dlg.Destroy()
        
    def ShowPic(self, filepath):
        self.CurrentImage = filepath
        self.ShowImage()
    def ShowImage(self):
        if len(self.CurrentImage)>0:
            img = wx.Image(self.CurrentImage, wx.BITMAP_TYPE_ANY)
            self.SetImage(img)
    def SetImage(self, img):
            OrigWidth = img.GetWidth()
            OrigHeight = img.GetHeight()
            PanelSize = self.GetClientSize()
            img = img.Scale(int(PanelSize[0] *( OrigHeight/ OrigWidth)), PanelSize[1] *0.65)   
            self.imageCtrl.SetBitmap(wx.BitmapFromImage(img))
            LeftMargin = int((PanelSize[0] - img.GetWidth())/2)
            self.imageCtrl.SetPosition( (LeftMargin, 0) )
            self.imageCtrl.Update()
            self.imageCtrl.Refresh()
    def OnSize(self, event):
        size = self.GetClientSize()
        height = int(size.height *0.65)
        self.picpanel.SetPosition( (0, height) )
        height = int(size.height *0.25)
        self.picpanel.SetSize(( size.width, height))
        height = int(size.height *0.10)
        self.logtb.SetSize( ( size.width, height) )
        self.logtb.SetPosition( ( 0, size.height -height) )
        self.ShowImage()
        if len(self.CurrentImage)>0:
            self.picpanel.Update()
            self.picpanel.Refresh()
        self.Update()
        self.Refresh()
    def About(self, event):
        info = wx.AboutDialogInfo()
        info.Name = AppName
        info.Version = Version
        info.Copyright = "(C) 2012 Davy Mitchell"
        info.Description = "Program for easily viewing Mojang's Minecraft screenshots."
        info.WebSite = ("http://daftpython.blogspot.co.uk", "DaftPython Blog")
        info.Developers = [ "Code by Davy Mitchell",
                            "Testing and Ideas by Niall Mitchell",
                            "Thanks to 'The Internet' for help, ideas and inspiration"]
        info.License = "New BSD"
        wx.AboutBox(info)
    def OpenFolder(self, event):
        if len(self.shotpath)>0:
            if os.name=="nt":
                subprocess.Popen('explorer "' + self.shotpath + '"')
            else:
                wx.MessageBox('Sorry this only works on Windows for now!', 'Info', wx.OK | wx.ICON_INFORMATION)
    def RefreshList(self, event):
        s = ScreenShots()
        s.CreateFromFolder(self.shotpath, ".png", True)
        self.Log("Shotpath [" + self.shotpath + "]")
        self.Log(str(len(s.ScreenShotFilenames)) + " Screenshots")
        
        for child in self.picpanel.GetChildren(): 
            child.Destroy() 
        for f in s.ScreenShotFilenames:
            self.picpanel.AddImage(f)
    def Log(self, msg):
        self.logtb.AppendText(msg + "\r\n")

class Preview(wx.StaticBitmap):
    def __init__(self, parent, filepath):
        img = wx.Image(filepath, wx.BITMAP_TYPE_ANY).Scale(ThumbWidth,ThumbHeight)
        wx.StaticBitmap.__init__(self, parent, wx.ID_ANY, wx.BitmapFromImage(img),size=(ThumbWidth,ThumbHeight))
        self.filepath = filepath
    def OnPicClick(self, event):
        TopFrame.ShowPic(self.filepath) 

class ThumbsPanel(scrolled.ScrolledPanel):
    def __init__(self, parent):
        scrolled.ScrolledPanel.__init__(self, parent, wx.ID_ANY)
        self.vbox = wx.BoxSizer(wx.HORIZONTAL)
        self.SetSizer(self.vbox)
        self.SetAutoLayout(1)
        self.SetupScrolling()
        self.H = ThumbHeight
        self.W = ThumbWidth

    def AddImage(self, filepath):
        imageCtrl = Preview(self, filepath)
        imageCtrl.Bind(wx.EVT_LEFT_DOWN, imageCtrl.OnPicClick)
        self.vbox.Add(imageCtrl, 0, wx.ALL, 5)
        self.Update()
        self.Layout()
        self.SetupScrolling()
        SizeFrame()
        imageCtrl.Update()
        imageCtrl.Refresh()
        
    def OnPicClick(self, event):
        print event

class ScreenShots(object):
    """
    This is a simple class for a SlideShow.
    """
    def __init__(self):
        self.ScreenShotFilenames = []

    def CreateFromFolder(self, FolderPath, FileExtension, Append):
        """
        Creates or adds to a SlideShow by loading Graphics from a specified path.
        """
        if Append==False:
            self.ScreenShotFilenames = []

        for root, dirs, files in os.walk(FolderPath, topdown=False):
            for name in files:
                if name.find(FileExtension):
                    self.ScreenShotFilenames.append( os.path.join(root, name) )

class  MSVApp(wx.App):
    def OnInit(self):
        global TopFrame
        frame =  MSVFrame(None, -1, AppName)
        frame.Show(True)
        self.SetTopWindow(frame)
        TopFrame = frame
        return True

def main():
    app =  MSVApp(0)
    app.MainLoop()

if __name__ == "__main__":
    main()
